package com.xcx.services.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcx.bo.CommLogUserOperation;
import com.xcx.common.dto.base.BaseDto;
import com.xcx.common.dto.base.BaseResp;
import com.xcx.common.services.CommService;
import com.xcx.common.utils.CheckParamUtils;
import com.xcx.common.utils.ExceptionUtils;
import com.xcx.common.utils.HttpUtils;
import com.xcx.common.utils.IdGenUtils;
import com.xcx.dao.CommLogUserOperationDao;
import com.xcx.dto.CommLogUserOperationReq;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * 公共配置类
 */
@Slf4j
@Service
public class CommServiceImpl implements CommService {


    @Resource
    private CommLogUserOperationDao commLogUserOperationDao;

    /**
     * 保存用户信息
     *
     * @param reqStr
     * @return
     */
    @Override
    public String recordInfo(String reqStr) {
        log.info("recordInfo.req:{}", reqStr);
        BaseResp baseResp = new BaseResp();
        try {
            CheckParamUtils.validateReqString(reqStr);
            CommLogUserOperationReq baseReq = BaseDto.fromJson(reqStr, CommLogUserOperationReq.class);
            CheckParamUtils.validateReqGson(baseReq);

            CommLogUserOperation opt = new CommLogUserOperation();
            opt.setOperationNo(IdGenUtils.uuid());
            opt.setUserNo(baseReq.getUserNo());
            opt.setLatitude(baseReq.getLatitude());
            opt.setLongitude(baseReq.getLongitude());
            opt.setDeviceInfo(baseReq.getDeviceInfo());
            JSONObject obj;
            int num = 0;
            do {
                String url = "http://maps.google.cn/maps/api/geocode/json";
                Map<String, Object> map = new HashMap<>(1);
                map.put("latlng", baseReq.getLatitude() + "," + baseReq.getLongitude());
                StringBuffer sb = HttpUtils.URLGet(url, map, 10 * 1000);
                obj = JSON.parseObject(sb.toString());
                num++;
            } while (!"OK".equals(obj.get("status")) && num <= 3);
            if ("OK".equals(obj.get("status"))) {
                JSONArray results = (JSONArray) obj.get("results");
                JSONObject object1 = (JSONObject) results.get(0);
                opt.setAddress((String) object1.get("formatted_address"));
            }
            commLogUserOperationDao.insert(opt);

            baseResp.buildDefaultSuccessResp(baseReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("CommServiceImpl", reqStr, baseResp, e.getMessage(), e);
        }
        log.info("recordInfo.resp:{}", baseResp.toString());
        return baseResp.toString();


    }
}
